package com.waigoulin.common.lbs;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @FileName IpLocationUtil
 * @Description 获取ip地址解析响应对象
 * @Author waigoulin
 * @date 2025-07-24
 **/
public class IpLocationUtil {
    public static String getLoginIp() {
        // 从当前线程中获取HttpServletRequest
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            return "未知IP"; // 非Web环境下返回默认值
        }
        HttpServletRequest request = attributes.getRequest();

        // 解析IP（同之前的逻辑）
        String[] ipHeaders = {"X-Forwarded-For", "Proxy-Client-IP", "WL-Proxy-Client-IP",
                "HTTP_CLIENT_IP", "HTTP_X_FORWARDED_FOR"};
        String ip = null;
        for (String header : ipHeaders) {
            ip = request.getHeader(header);
            if (ip != null && !ip.isEmpty() && !"unknown".equalsIgnoreCase(ip)) {
                if (ip.contains(",")) {
                    ip = ip.split(",")[0].trim();
                }
                return ip;
            }
        }
        ip = request.getRemoteAddr();
        if ("127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip)) {
            ip = "127.0.0.1";
        }
        return ip;
    }
}


